package com.myapp.ruyixing.ui;

import static android.view.View.GONE;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.Config;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.Model;
import com.myapp.ruyixing.model.ShopDetail;
import com.myapp.ruyixing.model.ShopDetail.DetailItem;
import com.myapp.ruyixing.ui.widget.PickPhoneCallFragment;
import com.myapp.ruyixing.utils.BitmapLruCache;
import com.myapp.ruyixing.utils.LoginHelper;
import com.myapp.ruyixing.utils.UIUtils;

public class ShopDetailActivity extends BaseActivity {

	public static final String INTENT_SHOP_ID = "shopid";
	public static final String INTENT_SHOP_NAME = "shopname";

	private String mShopId;
	private String mShopName;
	private ShopDetail mShopDetail;

	private RYHttpResponseHandler mFavoriteHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			try {
				Model model = (Model) o;
				if (model != null && model.errno == 0) {
					ImageView img = (ImageView) findViewById(R.id.img_favorite);
					img.setSelected(!img.isSelected());
					showLoading(false, null);
				} else {
					onFailure();
				}
			} catch (Exception e) {
				onFailure(e);
			}
		}

		private void onFailure() {
			showLoading(false, null);
			showToast("操作失败");
		}

		@Override
		public void onFailure(Throwable throwable) {
			onFailure();
		}
	};

	private OnClickListener mClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			boolean favorite = findViewById(R.id.img_favorite).isSelected();
			showLoading(true, "加载中");
			if (favorite) {
				RYHttpClient.delFavorite(ShopDetailActivity.this,
						mFavoriteHandler, LoginHelper.getInstance().getBDUSS(),
						mShopId);
			} else {
				RYHttpClient.submitFavorite(ShopDetailActivity.this,
						mFavoriteHandler, LoginHelper.getInstance().getBDUSS(),
						mShopId);
			}
		}
	};

	private RYHttpResponseHandler mHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			// try {
			ShopDetail shopDetail = (ShopDetail) o;
			mShopDetail = shopDetail;
			onLoadingDataFinished(true, shopDetail);
			// } catch (Exception e) {
			// onLoadingDataFinished(false, null);
			// }
		}

		@Override
		public void onFailure(Throwable throwable) {
			onLoadingDataFinished(false, null);
		}
	};

	public static void startShopDetailActivity(Context context, String shopid) {
		if (context == null || TextUtils.isEmpty(shopid)) {
			return;
		}
		Intent intent = new Intent(context, ShopDetailActivity.class);
		intent.putExtra("shopid", shopid);
		context.startActivity(intent);
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	private void showLoading(boolean show, String msg) {
		if (isFinishing()) {
			return;
		}
		if (show) {
			findViewById(R.id.layout_loading).setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.text_loading)).setText(msg);
		} else {
			findViewById(R.id.layout_loading).setVisibility(GONE);
		}
	}

	private void onLoadingDataStarted(String shopid, double lat, double lon) {
		showLoading(true, "加载中");
		RYHttpClient.getShopDetail(this, mHttpResponseHandler, shopid,
				LoginHelper.getInstance().getBDUSS(), lat, lon);
	}

	private void onLoadingDataFinished(boolean succeed, ShopDetail shopDetail) {
		if (succeed && shopDetail != null) {
			loadViews(shopDetail);
		} else {
			showToast("加载商户失败！");
		}
		showLoading(false, "");
	}

	private void loadViews(final ShopDetail shopDetail) {
		findViewById(R.id.layout_head).setVisibility(View.VISIBLE);
		if (TextUtils.isEmpty(LoginHelper.getInstance().getBDUSS())) {
			findViewById(R.id.img_favorite).setVisibility(View.GONE);
		} else {
			findViewById(R.id.img_favorite).setVisibility(View.VISIBLE);
			findViewById(R.id.img_favorite).setSelected(
					shopDetail.favorite == 1);
			findViewById(R.id.img_favorite).setOnClickListener(mClickListener);
		}
		if (shopDetail.distance >= 0) {
			String distance = "";
			if (shopDetail.distance >= 1000) {
				if (shopDetail.distance >= 1000000) {
					distance = "999+km";
				} else {
					distance = String.format("%.1fkm",
							((double) shopDetail.distance) / 1000);
				}
			} else {
				distance = shopDetail.distance + "m";
			}
			((TextView) findViewById(R.id.text_distance)).setText(distance);
		} else {
			((TextView) findViewById(R.id.text_distance))
					.setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(shopDetail.price)) {
			((TextView) findViewById(R.id.text_price))
					.setText(shopDetail.price);
		} else {
			((TextView) findViewById(R.id.text_price)).setText("");
		}
		if (!TextUtils.isEmpty(shopDetail.environment)) {
			((TextView) findViewById(R.id.text_ws))
					.setText(shopDetail.environment);
		} else {
			findViewById(R.id.text_ws).setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(shopDetail.taste)) {
			((TextView) findViewById(R.id.text_kw)).setText(shopDetail.taste);
		} else {
			findViewById(R.id.text_kw).setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(shopDetail.service)) {
			((TextView) findViewById(R.id.text_fw)).setText(shopDetail.service);
		} else {
			findViewById(R.id.text_fw).setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(shopDetail.name)) {
			mShopName = shopDetail.name;
			((TextView) findViewById(R.id.text_shop_name))
					.setText(shopDetail.name);
		} else {
			((TextView) findViewById(R.id.text_shop_name))
					.setVisibility(View.GONE);
		}
		if (shopDetail.score >= 0 && shopDetail.score <= 5) {
			((TextView) findViewById(R.id.text_score)).setText(shopDetail.score
					+ "");
			((ImageView) findViewById(R.id.score))
					.setImageLevel(shopDetail.score);
		}
		if (!TextUtils.isEmpty(shopDetail.picurl)) {
			RequestQueue mQueue = Volley
					.newRequestQueue(ShopDetailActivity.this);
			ImageLoader mImageLoader = new ImageLoader(mQueue,
					new BitmapLruCache());
			((NetworkImageView) findViewById(R.id.shop_image)).setImageUrl(
					shopDetail.picurl, mImageLoader);
			((NetworkImageView) findViewById(R.id.shop_image))
					.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							startActivity(new Intent(ShopDetailActivity.this,
									ShopAlbumActivity.class).putExtra(
									INTENT_SHOP_ID, mShopId).putExtra(
									INTENT_SHOP_NAME, mShopName));
						}
					});
		}
		if (!TextUtils.isEmpty(shopDetail.othershop)
				&& shopDetail.othershop.equals("1")) {
			View shop = findViewById(R.id.view_shop);
			shop.setVisibility(View.VISIBLE);
			shop.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startActivity(new Intent(ShopDetailActivity.this,
							OtherShopActivity.class).putExtra(INTENT_SHOP_ID,
							mShopId).putExtra(INTENT_SHOP_NAME, mShopName));
				}
			});
		}
		LinearLayout content = (LinearLayout) findViewById(R.id.layout_content);
		if (shopDetail.list != null && shopDetail.list.size() > 0) {
			View time_view = content.findViewById(R.id.view_time);
			time_view.setVisibility(View.VISIBLE);
			time_view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startActivity(new Intent(ShopDetailActivity.this,
							ShopTrafficAndTimeActivity.class).putExtra(
							INTENT_SHOP_ID, mShopId).putExtra(INTENT_SHOP_NAME,
							mShopName));

				}
			});
			View nearby_view = content.findViewById(R.id.view_nearby);
			nearby_view.setVisibility(View.VISIBLE);
			nearby_view.findViewById(R.id.layout_food).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							startActivity(new Intent(ShopDetailActivity.this,
									NearbyStoreActivity.class)
									.putExtra(
											NearbyStoreActivity.INTENT_KEY_TYPE,
											"food")
									.putExtra(
											NearbyStoreActivity.INTENT_LATITUDE,
											mShopDetail.lat)
									.putExtra(
											NearbyStoreActivity.INTENT_LONGTUDE,
											mShopDetail.lon));

						}
					});
			nearby_view.findViewById(R.id.layout_scene).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							startActivity(new Intent(ShopDetailActivity.this,
									NearbyStoreActivity.class)
									.putExtra(
											NearbyStoreActivity.INTENT_KEY_TYPE,
											"travel")
									.putExtra(
											NearbyStoreActivity.INTENT_LATITUDE,
											mShopDetail.lat)
									.putExtra(
											NearbyStoreActivity.INTENT_LONGTUDE,
											mShopDetail.lon));

						}
					});
			nearby_view.findViewById(R.id.layout_hotel).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							startActivity(new Intent(ShopDetailActivity.this,
									NearbyStoreActivity.class)
									.putExtra(
											NearbyStoreActivity.INTENT_KEY_TYPE,
											"hotel")
									.putExtra(
											NearbyStoreActivity.INTENT_LATITUDE,
											mShopDetail.lat)
									.putExtra(
											NearbyStoreActivity.INTENT_LONGTUDE,
											mShopDetail.lon));
						}
					});
			nearby_view.findViewById(R.id.layout_all).setOnClickListener(
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							startActivity(new Intent(ShopDetailActivity.this,
									NearbyStoreActivity.class)
									.putExtra(
											NearbyStoreActivity.INTENT_KEY_TYPE,
											"entertainment")
									.putExtra(
											NearbyStoreActivity.INTENT_LATITUDE,
											mShopDetail.lat)
									.putExtra(
											NearbyStoreActivity.INTENT_LONGTUDE,
											mShopDetail.lon));
						}
					});
			for (DetailItem item : shopDetail.list) {
				View child = null;
				if (item != null && !TextUtils.isEmpty(item.type)) {
					if ("address".equals(item.type)) {
						child = content.findViewById(R.id.view_address);
						child.setVisibility(View.VISIBLE);
						((TextView) child.findViewById(R.id.text_address))
								.setText(item.content);
						child.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								onShowMap(shopDetail.lat, shopDetail.lon,
										shopDetail.name);
							}
						});
					} else if ("phone".equals(item.type)) {
						child = content.findViewById(R.id.view_phone);
						child.setVisibility(View.VISIBLE);
						((TextView) child.findViewById(R.id.text_phone))
								.setText("" + item.content);
						final String phoneNumber = item.content;
						child.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								onPhoneCallClicked(phoneNumber);
							}
						});
					} else if ("order".equals(item.type)) {
						child = content.findViewById(R.id.view_reservation);
						child.setVisibility(View.VISIBLE);
						((TextView) child.findViewById(R.id.text_present))
								.setText(item.content + "积分");
						child.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								if (!LoginHelper.getInstance().ensureLogin(
										ShopDetailActivity.this)) {
									return;
								}

								ReservationActivity.startReservationActivity(
										ShopDetailActivity.this, mShopId);
							}
						});
					} else if ("orderserve".equals(item.type)) {
						child = content.findViewById(R.id.view_member);
						child.setVisibility(View.VISIBLE);
						((TextView) child.findViewById(R.id.text_member))
								.setText(item.content);
						child.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {

								startActivity(new Intent(
										ShopDetailActivity.this,
										MemberActivity.class));
							}
						});
					} else if ("preferential".equals(item.type)) {
						child = content.findViewById(R.id.view_highlight);
						child.setVisibility(View.VISIBLE);
						((TextView) child.findViewById(R.id.text_title))
								.setText(item.title);
						((TextView) child.findViewById(R.id.text_content))
								.setText(item.content);
						final String id = item.id;
						child.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								DiscountDetailActivity
										.startDiscountDetailActivity(
												ShopDetailActivity.this, id);
							}
						});
					} else if ("recommended".equals(item.type)) {
						child = content.findViewById(R.id.view_recommend);
						child.setVisibility(View.VISIBLE);
						((TextView) child.findViewById(R.id.text_title))
								.setText(item.title);
						((TextView) child.findViewById(R.id.text_content))
								.setText(item.content);
					} else if ("review".equals(item.type)) {
						child = content.findViewById(R.id.view_remark);
						child.setVisibility(View.VISIBLE);
						child.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								startActivity(new Intent(
										ShopDetailActivity.this,
										ShopRemarkListActivity.class).putExtra(
										INTENT_SHOP_ID, mShopId).putExtra(
										INTENT_SHOP_NAME, mShopName));
							}
						});
						((TextView) child.findViewById(R.id.text_title))
								.setText(item.title + "(共" + item.total + "条)");
						((TextView) child.findViewById(R.id.text_name))
								.setText(item.username);
						((TextView) child.findViewById(R.id.text_content))
								.setText(item.content);
						((TextView) child.findViewById(R.id.text_time))
								.setText(item.datetime);
						if (item.score >= 0 && item.score <= 5) {
							((ImageView) child.findViewById(R.id.score))
									.setImageLevel(item.score);
						}
					} else if ("signin".equals(item.type)) {
						child = content.findViewById(R.id.view_registration);
						child.setVisibility(View.VISIBLE);
						child.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								startActivity(new Intent(
										ShopDetailActivity.this,
										ShopRegistrationListActivity.class)
										.putExtra(INTENT_SHOP_ID, mShopId)
										.putExtra(INTENT_SHOP_NAME, mShopName));

							}
						});
						((TextView) child.findViewById(R.id.text_title))
								.setText(item.title + "(共" + item.total + "条)");
						((TextView) child.findViewById(R.id.text_name))
								.setText(item.username);
						((TextView) child.findViewById(R.id.text_time))
								.setText(item.datetime);
						if (item.score >= 0 && item.score <= 5) {
							((ImageView) child.findViewById(R.id.score))
									.setImageLevel(item.score);
						}
						if (!TextUtils.isEmpty(shopDetail.picurl)) {
							RequestQueue mQueue = Volley
									.newRequestQueue(ShopDetailActivity.this);
							ImageLoader mImageLoader = new ImageLoader(mQueue,
									new BitmapLruCache());
							((NetworkImageView) child.findViewById(R.id.avatar))
									.setImageUrl(item.avatar, mImageLoader);
						}
					}
				}
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shop_detail);
		findViewById(R.id.img_icon).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		findViewById(R.id.button_report).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (Config
								.isShopManagerVersionAndNotBinded(ShopDetailActivity.this)) {
							showToast("您未绑定会员账号，请绑定后再使用此功能");
						} else {

							if (!LoginHelper.getInstance().ensureLogin(
									ShopDetailActivity.this)) {
								return;
							}

							startActivity(new Intent(ShopDetailActivity.this,
									ShopErrorReportActivity.class).putExtra(
									INTENT_SHOP_ID, mShopId).putExtra(
									INTENT_SHOP_NAME, mShopName));
						}

					}
				});
		findViewById(R.id.button_upload).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (Config
								.isShopManagerVersionAndNotBinded(ShopDetailActivity.this)) {
							showToast("您未绑定会员账号，请绑定后再使用此功能");
						} else {

							if (!LoginHelper.getInstance().ensureLogin(
									ShopDetailActivity.this)) {
								return;
							}

							startActivity(new Intent(ShopDetailActivity.this,
									UploadPhotoActivity.class).putExtra(
									INTENT_SHOP_ID, mShopId).putExtra(
									INTENT_SHOP_NAME, mShopName));
						}

					}
				});
		findViewById(R.id.button_signin).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (Config
								.isShopManagerVersionAndNotBinded(ShopDetailActivity.this)) {
							showToast("您未绑定会员账号，请绑定后再使用此功能");
						} else {

							if (!LoginHelper.getInstance().ensureLogin(
									ShopDetailActivity.this)) {
								return;
							}

							startActivity(new Intent(ShopDetailActivity.this,
									ShopAddRegistrationActivity.class)
									.putExtra(INTENT_SHOP_ID, mShopId)
									.putExtra(INTENT_SHOP_NAME, mShopName));
						}

					}
				});
		findViewById(R.id.button_remark).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (Config
								.isShopManagerVersionAndNotBinded(ShopDetailActivity.this)) {
							showToast("您未绑定会员账号，请绑定后再使用此功能");
						} else {

							if (!LoginHelper.getInstance().ensureLogin(
									ShopDetailActivity.this)) {
								return;
							}

							startActivity(new Intent(ShopDetailActivity.this,
									ShopAddRemarkActivity.class).putExtra(
									INTENT_SHOP_ID, mShopId).putExtra(
									INTENT_SHOP_NAME, mShopName));
						}

					}
				});
		mShopId = getIntent().getStringExtra("shopid");
		if (TextUtils.isEmpty(mShopId)) {
			finish();
			return;
		}
		onLoadingDataStarted(mShopId, Config.sMyLocation.getLatitude(),
				Config.sMyLocation.getLongitude());
	}

	private void onPhoneCallClicked(String phoneNumber) {
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
		if (prev != null) {
			return;
		}
		ft.addToBackStack(null);

		// Create and show the dialog.
		DialogFragment newFragment = PickPhoneCallFragment.newInstance(
				UIUtils.findPhoneNumbers(phoneNumber), mShopId);
		newFragment.show(ft, "dialog");
	}

	private void onShowMap(double lat, double lon, String name) {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:"
					+ lat + "," + lon + "?q=" + lat + "," + lon + "(" + name
					+ ")"));
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
			Intent browserIntent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("http://api.map.baidu.com/marker?location=" + lat
							+ "," + lon + "&title=" + name + "&output=html"));
			startActivity(browserIntent);
		}
	}
}
